/**
 * 桩函数编辑接口测试用例
 *
 * Created by snowingsea on 2020/03/07.
 */
const chai = require('chai');
const should = chai.should(); // eslint-disable-line no-unused-vars
chai.use(require('chai-http'));
const randomstring = require('randomstring');

const common = require('./../../../common');
const Administrator = require('./../../../../models/administrator');
const uri = require('./../../uri');
const benchmark = require('./../../../../benchmark/analyse-files/logic_bombs');

module.exports = describe('/PUT functions/:id/stubs/stubName.json', function () {
  const administrator = new Administrator();
  const newUserIds = [];
  let projectVersion = {};
  let func = {};
  let functionId;
  let stubName;

  function url(functionId, stubName) {
    return `/functions/${functionId}/stubs/${stubName}.json`;
  }

  before(function (done) {
    administrator.login()
      .then(() => administrator.createRandomTester())
      .then((tester) => {
        newUserIds.push(tester.userId);
        return tester.createRandomProject();
      })
      .then((project) => project.createRandomVersion())
      .then((res) => {
        projectVersion = res;
        return projectVersion.getAllStubs(benchmark);
      })
      .then(([item]) => {
        functionId = item.functionId;
        stubName = item.stubName;
        return projectVersion.generateSimpleFunctionModel(functionId, '', '');
      })
      .then((f) => {
        func = f;
        done();
      })
      .catch(done);
  });
  after(function (done) {
    administrator.removeUsers(newUserIds)
      .then(() => {
        done();
      })
      .catch(done);
  });

  common.should.be.user(uri, url, 'put');
  common.should.be.tester(uri, url, 'put');

  const addQuery1 = {
    returnType: 'int',
    paramTypeNames: ['int', 'int', 'int'],
    paramNames: ['1', '2', '3'],
    times: '7',
  };
  const addQuery2 = JSON.parse(JSON.stringify(addQuery1));
  delete addQuery2.returnType;
  const addQuery3 = JSON.parse(JSON.stringify(addQuery1));
  delete addQuery3.paramNames;
  const addQuery4 = JSON.parse(JSON.stringify(addQuery1));
  delete addQuery4.times;
  const addQuery5 = JSON.parse(JSON.stringify(addQuery1));
  delete addQuery5.paramNames;
  delete addQuery5.paramTypeNames;
  const addStubQuerys = [addQuery1, addQuery2, addQuery3, addQuery4, addQuery5];

  const editQuery1 = {
    newStubName: randomstring.generate({ length: 16, charset: 'alphabetic' }),
    paramNames: ['4', '5', '6'],
    times: '9',
  };
  const editQuery2 = JSON.parse(JSON.stringify(editQuery1));
  delete editQuery2.newStubName;
  const editQuery3 = JSON.parse(JSON.stringify(editQuery1));
  delete editQuery3.paramNames;
  const editQuery4 = JSON.parse(JSON.stringify(editQuery1));
  delete editQuery4.times;
  const editStubQuerys = [editQuery1, editQuery2, editQuery3, editQuery4];

  const descartes = [];
  addStubQuerys.forEach((addQuery) => {
    editStubQuerys.forEach((editQuery) => {
      descartes.push({ addQuery, editQuery });
    });
  });

  // 正常编辑
  descartes.forEach(({ addQuery, editQuery }) => {
    if (addQuery.paramTypeNames || !editQuery.paramNames) {
      it('it should UPDATE stub sccessed', function (done) {
        addQuery.stubName = randomstring.generate({ length: 16, charset: 'alphabetic' });
        editQuery.newStubName = randomstring.generate({ length: 16, charset: 'alphabetic' });
        func.addStub(addQuery)
          .then(() => {
            chai.request(uri)
              .put(url(func.functionId, addQuery.stubName))
              .set('Authorization', `Bearer ${projectVersion.project.creator.token.accessToken}`)
              .query(editQuery)
              .end((err, res) => {
                res.should.have.status(200);
                common.should.be.functionStubMessage(res.body);
                res.body.functionId.should.be.eql(func.functionId);
                common.should.be.stubValidParam(res.body.params);
                done();
              });
          })
          .catch(done);
      });
    }
  });

  const invalidEditQuery1 = JSON.parse(JSON.stringify(editQuery1));
  invalidEditQuery1.paramNames.pop();
  const invalidEditQuery2 = JSON.parse(JSON.stringify(editQuery1));
  // eslint-disable-next-line prefer-destructuring
  invalidEditQuery2.paramNames[1] = invalidEditQuery2.paramNames[0];
  const invalidUpdateQuerys = [invalidEditQuery1, invalidEditQuery2];

  // paramNames非空时，如果其中存在相同的参数名，或其长度与paramTypeNames长度不一致,不可编辑
  invalidUpdateQuerys.forEach((updateQuery) => {
    it('it should not update invalid stub', function (done) {
      addQuery1.stubName = randomstring.generate({ length: 16, charset: 'alphabetic' });
      updateQuery.newStubName = randomstring.generate({ length: 16, charset: 'alphabetic' });
      func.addStub(addQuery1)
        .then(() => projectVersion.project.creator.login())
        .then(() => {
          chai.request(uri)
            .put(url(func.functionId, addQuery1.stubName))
            .set('Authorization', `Bearer ${projectVersion.project.creator.token.accessToken}`)
            .query(updateQuery)
            .end((err, res) => {
              res.should.have.status(400);
              common.should.be.errorMessage(res.body);
              done();
            });
        })
        .catch(done);
    });
  });

  // 无法编辑不可编辑的桩函数
  it('it should not update stub not modifiable', function (done) {
    projectVersion.project.creator.login()
      .then(() => {
        chai.request(uri)
          .put(url(functionId, stubName))
          .set('Authorization', `Bearer ${projectVersion.project.creator.token.accessToken}`)
          .query({ paramNames: ['4', '5', '6'] })
          .end((err, res) => {
            res.should.have.status(416);
            common.should.be.errorMessage(res.body);
            done();
          });
      })
      .catch(done);
  });

  // 函数不存在时无法编辑相应的桩函数
  it('it should fail to update stub when the function is not exists', function (done) {
    const stubName = randomstring.generate({ length: 16, charset: 'alphabetic' });
    new Promise((resolve) => {
      chai.request(uri)
        .put(url('000000000000000000000000', stubName))
        .set('Authorization', `Bearer ${projectVersion.project.creator.token.accessToken}`)
        .end((err, res) => {
          res.should.have.status(404);
          common.should.be.errorMessage(res.body);
          resolve();
        });
    })
      .then(done)
      .catch(done);
  });

  // 不可编辑他人项目的桩函数
  it('it should fail to update stub when the project is not yours', function (done) {
    let newUser;
    const stubName = randomstring.generate({ length: 16, charset: 'alphabetic' });
    administrator.createRandomTester()
      .then((tester) => {
        newUser = tester;
        newUserIds.push(tester.userId);
        return tester.getToken();
      })
      .then(() => projectVersion.project.creator.login())
      .then(() => {
        chai.request(uri)
          .put(url(func.functionId, stubName))
          .set('Authorization', `Bearer ${newUser.token.accessToken}`)
          .end((err, res) => {
            res.should.have.status(404);
            common.should.be.errorMessage(res.body);
            done();
          });
      })
      .catch(done);
  });

  // 桩函数不存在时无法编辑
  it('it should not update stub not exists', function (done) {
    chai.request(uri)
      .put(url(func.functionId, randomstring.generate({ length: 16, charset: 'alphabetic' })))
      .set('Authorization', `Bearer ${projectVersion.project.creator.token.accessToken}`)
      .end((err, res) => {
        res.should.have.status(404);
        common.should.be.errorMessage(res.body);
        done();
      });
  });
});
